import asyncio
import os
from mcp import ClientSession, StdioServerParameters, types
from mcp.client.stdio import stdio_client
from pydantic import AnyUrl


async def main() -> None:
    # 获取当前文件的绝对路径所在的目录
    base_dir = os.path.dirname(os.path.abspath(__file__))
    server_path = os.path.join(base_dir, "lowlevel_server.py")
    server_params = StdioServerParameters(command="python", args=[server_path], env={})
    async with stdio_client(server_params) as (read_stream, write_stream):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()
            tools = await session.list_tools()
            print("[Tools]", [t.name for t in tools.tools])
            tool_result = await session.call_tool(
                "query_db", {"query": "SELECT * from users"}
            )
            structuredContent = getattr(tool_result, "structuredContent", None)
            if structuredContent:
                print("[structuredContent output]", structuredContent)
            else:
                texts = []
                for block in tool_result.content:
                    if isinstance(block, types.TextContent):
                        texts.append(block.text)
                print("[Text Content]", "|".join(texts))

            resources = await session.list_resources()
            print("[tool resources]", [r.name for r in resources.resources])

            resource_result = await session.read_resource(AnyUrl("data://status"))
            texts = []
            for block in resource_result.contents:
                if isinstance(block, types.TextResourceContents):
                    texts.append(block.text)
            print("[resource Content]", "|".join(texts))


if __name__ == "__main__":
    asyncio.run(main())
